package com.tianyang.yukuaifuzs.business.main.view;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tencent.smtt.export.external.interfaces.JsPromptResult;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tianyang.yukuaifuzs.R;
import com.tianyang.yukuaifuzs.base.BaseTitleActivity;
import com.tianyang.yukuaifuzs.business.main.bean.BrowserInput;
import com.tianyang.yukuaifuzs.business.main.contract.BrowserX5Contract;
import com.tianyang.yukuaifuzs.business.main.contract.MainConfig;
import com.tianyang.yukuaifuzs.business.main.interfaces.IValueCallbackListener;
import com.tianyang.yukuaifuzs.business.main.presenter.BrowserX5Presenter;
import com.tianyang.yukuaifuzs.common.interfaces.CommonConfig;
import com.tianyang.yukuaifuzs.common.view.RippleLoadingDialog;
import com.tianyang.yukuaifuzs.common.view.X5WebView;
import com.tianyang.yukuaifuzs.jump.jsbridge.JsBridge;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description：集成Tencent X5 Activity
 */

public class BrowserX5Activity extends BaseTitleActivity implements BrowserX5Contract.View {

    @BindView(R.id.progressBar)
    ProgressBar vProgressBar;
    @BindView(R.id.shareIv)
    ImageView vShare;
    @BindView(R.id.titleTv)
    TextView vTitleTv;
    @BindView(R.id.webView)
    FrameLayout vViewParent;
    @BindView(R.id.titleLayout)
    RelativeLayout vTitleLayout;

    private BrowserX5Contract.Presenter mPresenter;

    private RippleLoadingDialog mLoadingDialog;

    private X5WebView mWebView;

    private JsBridge mJsBridge;

    private static int REQUESTCODE_WXPAY = 9999;

    private ValueCallback<Uri> mUploadMessage;// 表单的数据信息
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private Uri imageUri;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_web;
    }

    @Override
    protected void initView() {
        super.initView();
        mWebView = new X5WebView(this, null);
        mJsBridge = JsBridge.loadModule();

        vViewParent.addView(mWebView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT));
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebContentsDebuggingEnabled(true);

        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                vProgressBar.setVisibility(View.GONE);
                dismissPreLoading();
                if (TextUtils.isEmpty(vTitleTv.getText()) && mWebView.getTitle() != null) {
                    vTitleTv.setText(mWebView.getTitle());
                }
                mJsBridge.injectJs(view);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                try {
                    if (url.startsWith("weixin://wap/pay?")) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivityForResult(intent, REQUESTCODE_WXPAY);
                    }else {
                        return super.shouldOverrideUrlLoading(webView, url);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        });
        mWebView.setValueCallbackListener(new IValueCallbackListener() {
            @Override
            public void onJsPrompt(WebView webView, String url, String message, String s2, JsPromptResult result) {
                mJsBridge.callJsPrompt(message, result);
            }

            @Override
            public void onProgressChanged(WebView webView, int newProgress) {
                if (newProgress == 100) {
                    vProgressBar.setVisibility(View.GONE);
                } else {
                    if (vProgressBar.getVisibility() == View.GONE)
                        vProgressBar.setVisibility(View.VISIBLE);
                    vProgressBar.setProgress(newProgress);
                }
            }

            @Override
            public void callback(ValueCallback<Uri> uploadMessage, ValueCallback<Uri[]> uploadCallbackAboveL) {
                mUploadMessage = uploadMessage;
                mUploadCallbackAboveL = uploadCallbackAboveL;
            }

            @Override
            public void callback(Uri uri) {
                imageUri = uri;
            }
        });
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String s1, String s2, String s3, long l) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
        mWebView.addJavascriptInterface(new OnBusinessForHtml(), MainConfig.YKF);
    }

    @Override
    protected void initData() {
        super.initData();
        BrowserInput mInput = (BrowserInput)
                getIntent().getSerializableExtra(MainConfig.INTENT_BROWSER_INPUT);

        mPresenter = new BrowserX5Presenter(this);
        mPresenter.initViewData(mInput);
    }

    @OnClick({R.id.leftIv, R.id.closeIv, R.id.shareIv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leftIv:
                onBackPressed();
                break;
            case R.id.closeIv:
                finish();
                break;
        }
    }

    @Override
    public void showTitleLayout(String title, boolean isShow) {
        if (isShow) {
            vTitleLayout.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(title)) {
                vTitleTv.setText(title);
            }
        } else {
            vTitleLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void loadUrl(String url) {
        mWebView.loadUrl(url);
    }

    @Override
    public void loadUrl(String url, Map<String, String> extraHeaders) {
        mWebView.loadUrl(url, extraHeaders);
    }

    @Override
    public void loadDataWithBaseURL(String content) {
        mWebView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
    }

    @Override
    public void showPreLoading() {
        if (mLoadingDialog == null) {
            mLoadingDialog = new RippleLoadingDialog(mContext);
        } else {
            if (mLoadingDialog.isShowing()) {
                mLoadingDialog.dismiss();
            }
        }
        mLoadingDialog.show();
    }

    /**
     * 关闭加载框
     */
    private void dismissPreLoading() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent == null || mWebView == null || intent.getData() == null)
            return;
        mWebView.loadUrl(intent.getData().toString());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_WXPAY) {
            finish();
        } else if (requestCode == CommonConfig.WEB_REQUESTCODE_FILE_CHOOSE) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else  if (mUploadMessage != null) {
                if(result==null){
                    mUploadMessage.onReceiveValue(imageUri);
                    mUploadMessage = null;
                }else {
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;
                }
            }
        }
    }

    @SuppressWarnings("null")
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != CommonConfig.WEB_REQUESTCODE_FILE_CHOOSE || mUploadCallbackAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
                results = new Uri[]{imageUri};
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        if(results!=null){
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        }else{
            results = new Uri[]{imageUri};
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        }
        return;
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return false;
    }

    @Override
    protected boolean hasCommonTitle() {
        return false;
    }

    @Override
    public void setPresenter(BrowserX5Contract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        dismissPreLoading();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
        if (mWebView != null)
            mWebView.destroy();
        if (mJsBridge != null)
            mJsBridge.release();
        super.onDestroy();
    }

    /**
     * 内部类，定义关闭浏览器接口
     */
    private class OnBusinessForHtml {

        @JavascriptInterface
        public void backToPreviewPage() {
            finish();
        }
    }
}
